package com.kehongborui.fliggy.queue;

import com.kehongborui.fliggy.entity.Log;
import org.springframework.stereotype.Component;

import java.util.concurrent.LinkedBlockingQueue;

/**
 * @author zhang peng yang ming
 * @CopyRight (C) http://www.csdn.com
 * @brief
 * @email 122162005@qq.com
 * @date 2018-09-11
 */
public class CustomQueue {
    private static LinkedBlockingQueue queue;
    private int size;
    public static CustomQueue instance = new CustomQueue(300);
    public int length = 0;

    private CustomQueue() {
        size = 200;
        queue = new LinkedBlockingQueue(size);
    }

    private CustomQueue(int size) {
        queue = new LinkedBlockingQueue(size);
    }

    public static synchronized CustomQueue getInstance() {
        return instance;
    }

    public void push(Object o) {
        synchronized (queue) {  // 调用notify 的地方 锁对象必须存在
            try {
                queue.put(o);
                length++;
            } catch (InterruptedException e) {
                queue.notify();
                e.printStackTrace();
            }
            queue.notify();
        }
    }

    /**
     * 获取当前队列的长度
     * @return
     */
    public long length() {
        return queue.size();
    }

    public Object pop() {
        synchronized (queue) {
            if (length() == 0) {
                try {
                    queue.wait();
                } catch (InterruptedException e) {
                    queue.notify();
                    e.printStackTrace();
                }
            }
        }

        length++;
        return queue.poll();
    }
}
